package labox.innovation.gameserver.taskmanager;

import java.util.Collection;
import java.util.Map;

import javolution.util.FastMap;
import javolution.util.FastMap.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import labox.innovation.config.Config;
import labox.innovation.gameserver.model.FuzeWorld;
import labox.innovation.gameserver.model.actor.L2Character;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;
import labox.innovation.gameserver.model.actor.position.CharPosition;
import labox.innovation.gameserver.network.serverpackets.MoveToLocation;
import labox.innovation.gameserver.timer.Timer;
import labox.innovation.util.Point2D;

/**
 * 全局同步坐标任务
 * 
 * @author squll
 */
public final class SyncLocationTaskManager implements Runnable {

	protected static final Logger _log = LoggerFactory.getLogger(SyncLocationTaskManager.class.getName());

	private SyncLocationTaskManager() {
		new Timer(Config.SYNC_LOCATION_INTERVAL, true, this).start();
	}

	public static SyncLocationTaskManager getInstance() {
		return SingletonHolder._instance;
	}

	public void run() {
		FastMap<Long, L2Character> charactors = FuzeWorld.getInstance().getAllCharacters();
		CharPosition cp;
		Collection<FuzePcInstance> plrs;
		Point2D point;
		try {

			for (Entry<Long, L2Character> e = charactors.head(), n = charactors.tail(); (e = e.getNext()) != n;) {
				L2Character chara = e.getValue();
				if (chara.isDead())//死亡的角色不再同步坐标
					continue;
				cp = chara.getPosition();
				point = cp.getScenePosition();
				if (cp.equalPreScenePosition(point))//如果当前的坐标与上一次的坐标相同则不同步
					continue;
				cp.setPreScenePosition(point);

				plrs = chara.getKnownList().getKnownPlayers().values();
				MoveToLocation loc = new MoveToLocation(chara);
				for (FuzePcInstance player : plrs) {
					player.sendPacket(loc);
				}
			}
		} catch (Exception e) {
			_log.error("SyncLocationTaskManager error", Config.SERVER_ID, e);
		}
	}

	@Override
	public String toString() {
		String ret = "============= SyncLocation Manager Report ============\r\n";
		ret += "Tasks Interval: " + Config.SYNC_LOCATION_INTERVAL + "ms\r\n";
		ret += "Tasks Sync Player size:" + FuzeWorld.getInstance().getAllPlayersCount() + "\r\n";

		return ret;
	}

	@SuppressWarnings("synthetic-access")
	private static class SingletonHolder {
		protected static final SyncLocationTaskManager _instance = new SyncLocationTaskManager();
	}
}
